package vn.dinhnp.tourismdict;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.FacebookDialog.Callback;
import com.facebook.widget.FacebookDialog.PendingCall;

public class DetailContentFragment extends Fragment {

	private UiLifecycleHelper uiHelper;

	private GraphUser user;
	ImageButton voiceBT;
	ImageButton FbShare;
	ImageView image;
	TextView EnglishTv;
	TextView TranscriptionTv;
	TextView VietnameseTv;
	// DetailPhrase detailPhrase;

	public Integer Id;
	public Integer CategoryId;
	public String English;
	public String Decription;
	public String Transcription;
	public Integer IsSentence;
	public String Vietnamese;
	public Integer favourite;
	public String voice;
	public Integer Status;
	public SessionState myState;
	private Session.StatusCallback callback=new StatusCallback() {
		
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			// TODO Auto-generated method stub
			
		}
	};
	Context ct = getActivity();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		ViewGroup rootview = (ViewGroup) inflater.inflate(
				R.layout.fragment_detail_content, container, false);
		
		final Bundle _savedInstanceState=savedInstanceState;
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		Session session = Session.getActiveSession();
        if (session == null) {
            if (_savedInstanceState != null) {
                session = Session.restoreSession(getActivity(), null, callback, _savedInstanceState);
            }
            if (session == null) {
                session = new Session(getActivity());
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(getActivity()).setCallback(callback));
            }
        }
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);

		Log.e("database", "Lấy biến args ra");
		Bundle args = getArguments();
		Log.e("database", "Bắt đầu Truyền dữ liệu vào biến detailPhrase");
		try {
			Id = args.getInt("Id");
			CategoryId = args.getInt("CategoryId");
			English = args.getString("English");
			Decription = args.getString("Decription");
			Transcription = args.getString("Transcription");
			IsSentence = args.getInt("IsSentence");
			Vietnamese = args.getString("Vietnamese");
			favourite = args.getInt("favourite");
			voice = args.getString("voice");
			Status = args.getInt("Status");
		} catch (Exception e) {
			Log.e("database", "Lỗi : " + Id + " - " + args.getInt("Id"));
		}
		Log.e("database",
				"Truyền dữ liệu vào biến detailPhrase thành công");

		voiceBT = (ImageButton) rootview.findViewById(R.id.VoiceId);
		FbShare = (ImageButton) rootview.findViewById(R.id.ShareFbId);
		image = (ImageView) rootview.findViewById(R.id.image);
		EnglishTv = (TextView) rootview.findViewById(R.id.EnglishId);


//		URL url;
//		Bitmap bmp = null;
//		try {
//			url = new URL("https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-frc3/t1/10006999_682044121857760_358944701_n.jpg");
//			bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//		} catch (MalformedURLException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		if(bmp!=null)
//		image.setImageBitmap(bmp);
		ConnectivityManager cm = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		boolean isConnected = activeNetwork != null
				&& activeNetwork.isConnectedOrConnecting();

		if (isConnected)
		new DownloadImageTask(image).execute("https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-frc3/t1/10006999_682044121857760_358944701_n.jpg");


		TranscriptionTv = (TextView) rootview
				.findViewById(R.id.TranscriptionId);
		VietnameseTv = (TextView) rootview.findViewById(R.id.VietnameseId);

		voiceBT.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				int resID = getActivity().getResources().getIdentifier(
						voice + "_f", "raw", getActivity().getPackageName());

				if (resID == 0) {
					Toast.makeText(getActivity(),
							"Không tìm thấy dữ liệu âm thanh",
							Toast.LENGTH_SHORT).show();
					return;
				}

				final Uri myUri = Uri
						.parse("android.resource://vn.dinhnp.tourismdict/"
								+ resID); // initialize Uri here
				MediaPlayer mediaPlayer = new MediaPlayer();
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mediaPlayer.setDataSource(getActivity(), myUri);
					mediaPlayer.prepare();
				} catch (IllegalArgumentException e) {
					Toast.makeText(getActivity(), e.toString(),
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (SecurityException e) {
					Toast.makeText(getActivity(), e.toString(),
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (IllegalStateException e) {
					Toast.makeText(getActivity(), e.toString(),
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (IOException e) {
					Toast.makeText(getActivity(), e.toString(),
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}

				mediaPlayer.start();
				// Toast.makeText(getActivity(), myUri.toString(),
				// Toast.LENGTH_SHORT).show();

			}
		});

		FbShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ConnectivityManager cm = (ConnectivityManager) getActivity()
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
				boolean isConnected = activeNetwork != null
						&& activeNetwork.isConnectedOrConnecting();

				if (!isConnected)
					Toast.makeText(getActivity(),
							"Check the internet connection!!!",
							Toast.LENGTH_SHORT).show();
				else {
					//Bắt đầu Session
					
			        Session session = Session.getActiveSession();
			        if (!session.isOpened() && !session.isClosed()) 
			        {
			        	Toast.makeText(getActivity(),
								"Session chưa mở!!!",
								Toast.LENGTH_SHORT).show();
			            //session.openForRead(new Session.OpenRequest(getActivity()).setCallback(callback));
			        	session.openActiveSession(getActivity(), DetailContentFragment.this, true, callback);
			            if(Session.getActiveSession().isOpened())
			            {
			            	Toast.makeText(getActivity(),
									"Đã mở Session!!!",
									Toast.LENGTH_SHORT).show();
			            }
			            else
			            	Toast.makeText(getActivity(),
									"Chưa mở Session!!!",
									Toast.LENGTH_SHORT).show();
			            
			        } 
			        else 
			        {
			        	Toast.makeText(getActivity(),
								"Bắt đầu mở Session!!!",
								Toast.LENGTH_SHORT).show();
			            Session.openActiveSession(getActivity(),DetailContentFragment.this, true, callback);
			            if(Session.getActiveSession().isOpened())
			            {
			            	session=Session.getActiveSession();
			            	Toast.makeText(getActivity(),
									"Đã mở Session!!!",
									Toast.LENGTH_SHORT).show();
			            	if(!session.getPermissions().contains("publish_actions"))
			            	{
			            		Toast.makeText(getActivity(),
										"Chưa có quyền pushlish!!!",
										Toast.LENGTH_SHORT).show();
			            		session.requestNewPublishPermissions(new Session.NewPermissionsRequest(DetailContentFragment.this, "publish_actions"));
			            	}
			            	
			            	if(session.getPermissions().contains("publish_actions"))
			            	{
			            		Toast.makeText(getActivity(),
										"Đã cấp quyền pushlish!!!",
										Toast.LENGTH_SHORT).show();
			            	}
			            	
			            	if(user==null)
			            	{
			            		Request.newMeRequest(session, new GraphUserCallback() {
									
									@Override
									public void onCompleted(GraphUser _user, Response response) {
										// TODO Auto-generated method stub
										user=_user;
										Toast.makeText(getActivity(),
												" Đăng nhập với tên "
														+ user.getName(),
												Toast.LENGTH_SHORT)
												.show();
										postStatusFb();
									}
								}).executeAsync();
			            	}
			            	else
			            		postStatusFb();
			            }
			        }
					//Kết thúc Session
				}
			}
		});

		EnglishTv.setText(English);
		TranscriptionTv.setText("/" + Transcription + "/");
		VietnameseTv.setText(Vietnamese);
		return rootview;
	}

	// public void performNonSession()
	// {
	// if (Session.getActiveSession() == null ||
	// !Session.getActiveSession().isOpened())
	// {
	// Log.e("database", "Session is not open, start open");
	// Session.openActiveSession(getActivity(), true,callback);
	// performPublish();
	// }
	// }

	// public void performPublish()
	// {
	// Session session = Session.getActiveSession();
	// if (session != null)
	// {
	// if(user != null && session.getPermissions().contains("publish_actions"))
	// {
	// postStatusFb();
	// }
	// else
	// {
	// if (!session.getPermissions().contains("publish_actions"))
	// {
	// session.requestNewPublishPermissions(new
	// Session.NewPermissionsRequest(this, "publish_actions"));
	// }
	//
	// if(user!=null)
	// {
	// postStatusFb();
	// }
	// else
	// {
	// if (session.isOpened())
	// {
	// Request.newMeRequest(session,new GraphUserCallback() {
	//
	// @Override
	// public void onCompleted(GraphUser _user,Response response)
	// {
	// user = _user;
	// Toast.makeText(getActivity()," Đăng nhập facebook với tên "+
	// user.getName(),Toast.LENGTH_SHORT).show();
	// postStatusFb();
	// }
	// }).executeAsync();
	// }
	// }
	// }
	// }

	// if(FacebookDialog.canPresentShareDialog(getActivity(),FacebookDialog.ShareDialogFeature.SHARE_DIALOG))
	// {
	// postStatusFb();
	// }
	// }

	public void postStatusFb() {
		// TextView tv = (TextView) findViewById(R.id.text);
		// String content = tv.getText().toString();
		String content = "This is my favorite ";
		//Bitmap imgbm=image.getDrawingCache();


		Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();


		if (IsSentence == 0)
			content = content + "words ";
		else
			content = content + "sentenses ";
		content = content + "in TourismDict app :\n " + English + "\n /"
				+ Transcription + "/ \n" + Vietnamese;
		if (FacebookDialog.canPresentShareDialog(getActivity(),
				FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
			FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
					getActivity()).setName("Bói toàn").setDescription(content)
					.setLink("http://developers.facebook.com/android").build();
			uiHelper.trackPendingDialogCall(shareDialog.present());
		} else {
			if (user != null
					&& Session.getActiveSession().getPermissions()
							.contains("publish_actions")) {

				// Request request =
				// Request.newStatusUpdateRequest(Session.getActiveSession(),
				// content,new Request.Callback() {
				// @Override
				// public void onCompleted(Response response)
				// {
				// Toast.makeText(getActivity(),"Cập nhật thành công",Toast.LENGTH_SHORT).show();
				// }
				// });
				Request request = Request.newUploadPhotoRequest(Session
						.getActiveSession(),bitmap,//BitmapFactory.decodeResource(getResources(), R.drawable.characteristic),
						new Request.Callback() {

							@Override
							public void onCompleted(Response response) {
								Toast.makeText(getActivity(),
										"Cập nhật thành công",
										Toast.LENGTH_SHORT).show();
							}
						});
				Bundle parameters = request.getParameters(); // <-- THIS IS
																// IMPORTANT
				parameters.putString("message", content);
				// add more params here
				request.setParameters(parameters);
				request.executeAsync();
			} else {
				String msg = "";
				if (user == null)
					msg = msg + " User trống ";
				if (!Session.getActiveSession().getPermissions()
						.contains("publish_actions"))
					msg = msg + " Chưa cấp quyền ";
				if (Session.getActiveSession() == null)
					msg = msg + " Session trống ";
				Toast.makeText(getActivity(), "Chưa cập nhật được : " + msg,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getActivity(), requestCode,	resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data,
				new Callback() {

					@Override
					public void onError(PendingCall pendingCall,
							Exception error, Bundle data) {
						Log.e("Activity",
								String.format("Error: %s", error.toString()));

					}

					@Override
					public void onComplete(PendingCall pendingCall, Bundle data) {
						Log.i("Activity", "Success!");

					}
				});

	}
	
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		  ImageView bmImage;

		  public DownloadImageTask(ImageView bmImage) {
		      this.bmImage = bmImage;
		  }

		  protected Bitmap doInBackground(String... urls) {
		      String urldisplay = urls[0];
		      Bitmap mIcon11 = null;
		      try {
		        InputStream in = new java.net.URL(urldisplay).openStream();
		        mIcon11 = BitmapFactory.decodeStream(in);
		      } catch (Exception e) {
		          Log.e("Error", e.getMessage());
		          e.printStackTrace();
		      }
		      return mIcon11;
		  }

		  protected void onPostExecute(Bitmap result) {
		      bmImage.setImageBitmap(result);
		  }
		}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Session.getActiveSession().addCallback(callback);
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Session.getActiveSession().removeCallback(callback);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// uiHelper = new UiLifecycleHelper(getActivity(), callback);
		// uiHelper.onCreate(savedInstanceState);
	}
}
